import os
import requests
from mcp.server.fastmcp import FastMCP

# 初始化 MCP 服务器
mcp = FastMCP("RestaurantServer", host="127.0.0.1", port=8004)

def get_restaurants(location: str) -> str:
    """
    根据经纬度坐标获取1公里范围内餐饮场所信息
    :param location: 逗号分隔的经纬度字符串（如"116.397428,39.90923"）
    :return: 格式化后的餐饮场所信息
    """
    try:
        # 解析经纬度参数
        longitude, latitude = map(float, location.split(','))
        
        # 获取高德API密钥
        api_key = os.environ.get("AMAP_API_KEY")
        if not api_key:
            return "错误：未设置AMAP_API_KEY环境变量"
            
        # 构造API请求
        base_url = "https://restapi.amap.com/v3/place/around?"
        params = {
            "key": api_key,
            "location": f"{longitude},{latitude}",
            "keywords": "餐饮",
            "radius": "1000",
            "offset": "20",
            "extensions": "all"
        }
        
        # 发送请求
        response = requests.get(base_url, params=params, timeout=30)
        response.raise_for_status()
        
        # 解析响应
        data = response.json()
        if data.get("status") != "1":
            return f"API错误：{data.get('info', '未知错误')}"
            
        # 处理结果
        restaurants = []
        for poi in data.get("pois", [])[:5]:  # 取前5个结果
            restaurants.append({
                "name": poi.get("name"),
                "address": poi.get("address"),
                "type": poi.get("type"),
                "distance": poi.get("distance")
            })
            
        # 格式化输出
        result = f"周边餐饮场所（共{data.get('count', 0)}个，显示前5个）：\n\n"
        for r in restaurants:
            result += (
                f"名称：{r['name']}\n"
                f"类型：{r['type']}\n"
                f"地址：{r['address']}\n"
                f"距离：{r['distance']}米\n"
                "--------------------\n"
            )
            
        return result
        
    except requests.exceptions.RequestException as e:
        return f"网络请求失败：{str(e)}"
    except ValueError:
        return "错误：经纬度格式不正确，应为逗号分隔的两个数字"
    except Exception as e:
        return f"未知错误：{str(e)}"

@mcp.tool('query_restaurants', '查询当前位置周边餐饮场所')
def query_restaurants(location: str) -> str:
    """
    MCP工具函数：查询当前位置周边餐饮场所
    :param location: 逗号分隔的经纬度字符串
    """
    return get_restaurants(location)

if __name__ == "__main__":
    # 以 SSE 方式运行 MCP 服务器
    mcp.run(transport='sse')